package com.doubao.common.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;

import java.time.Duration;

/**
 * Lettuce连接池配置
 * 处理spring.data.redis.lettuce.pool相关配置
 */
@Configuration
@Slf4j
public class LettucePoolConfigurer {

    @Data
    @ConfigurationProperties(prefix = "spring.data.redis.lettuce.pool")
    public static class LettucePoolProperties {
        private int maxActive = 8;
        private int maxIdle = 8;
        private int minIdle = 0;
        private long maxWait = -1;
    }

    @Bean
    public LettucePoolProperties lettucePoolProperties() {
        return new LettucePoolProperties();
    }

    @Bean
    public LettucePoolingClientConfiguration lettucePoolingClientConfiguration(LettucePoolProperties lettucePoolProperties) {
        log.info("配置Lettuce连接池: maxActive={}, maxIdle={}, minIdle={}, maxWait={}",
                lettucePoolProperties.getMaxActive(),
                lettucePoolProperties.getMaxIdle(),
                lettucePoolProperties.getMinIdle(),
                lettucePoolProperties.getMaxWait());

        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(lettucePoolProperties.getMaxActive());
        poolConfig.setMaxIdle(lettucePoolProperties.getMaxIdle());
        poolConfig.setMinIdle(lettucePoolProperties.getMinIdle());
        poolConfig.setMaxWait(Duration.ofMillis(lettucePoolProperties.getMaxWait()));

        return LettucePoolingClientConfiguration.builder()
                .poolConfig(poolConfig)
                .commandTimeout(Duration.ofMillis(10000))
                .build();
    }
}